let timer = null
Component({
  data: {
    countDownTime: 1000,
    day: 0,
    hours: '00',
    minutes: '00',
    seconds: '00',
  },
  properties: {
    dateTime: 0
  },
  lifetimes: {
    attached: function () {
      // this.countDown()
      if (timer) clearInterval(timer);
      timer = setInterval(() => {
        this.countDown()
      }, 1000);
    },
    detached: function () {
      if (timer) clearInterval(timer);
    },
  },
  methods: {
    countDown() {
      const { dateTime } = this.properties
      const leftTime = new Date(dateTime) - Date.now()
      if (leftTime < 0) {
        this.triggerEvent('timeOut')
        if (timer) clearInterval(timer);
        return this.setData({
          hours: '00',
          minutes: '00',
          seconds: '00'
        })

      }
      const { hours, minutes, seconds, days } = this.parseMs(leftTime)
      let newHour = 0
      if (days > 0) {
        newHour = hours + days * 24
      }
      this.setData({
        hours: this.padNumber(newHour),
        minutes: this.padNumber(minutes),
        seconds: this.padNumber(seconds)
      }, () => {
        if (timer && leftTime <= 0) {
          clearInterval(timer)
        };
      })
    },
    parseMs(milliseconds) {
      return {
        days: Math.floor(milliseconds / 86400000),
        hours: Math.floor(milliseconds / 3600000) % 24,
        minutes: Math.floor(milliseconds / 60000) % 60,
        seconds: Math.floor(milliseconds / 1000) % 60,
        milliseconds: Math.floor(milliseconds) % 1000,
      };
    },
    padNumber(num) {
      if (num < 10) {
        return num.toString().padStart(2, '0')
      }
      return num
    }
  }
})